<template>
  <div style="margin: 20px 50px">
    <recursive-component ref="customRef" :schema="treeData" v-model="data"></recursive-component>
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import RecursiveComponent from './components/recursive-component.vue';
import type { TreeNode } from './types/interface';
import { ElForm, ElRow, ElCol, ElFormItem, ElInput, ElMessage, ElButton, type FormInstance } from 'element-plus';
import { nanoid } from 'nanoid';
defineOptions({
  name: 'PagePreview',
});
const customRef = ref();
const data = ref({ data: { name: '张三', sex: '男' } });

const treeData: TreeNode = {
  id: 'formRef',
  name: ElForm,
  model: 'data',
  attr: {
    labelWidth: '80px',
    model: 'data',
    rules: {
      name: [
        { required: true, message: 'Please input Activity name', trigger: 'blur' },
        { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
      ],
    },
  },
  children: [
    {
      id: nanoid(),
      name: ElRow,
      children: [
        {
          id: nanoid(),
          name: ElCol,
          attr: { span: 12 },
          children: [
            {
              id: nanoid(),
              name: ElFormItem,
              attr: { label: '姓名', prop: 'name' },
              children: [{ id: nanoid(), name: ElInput, attr: { size: 'small', valueField: 'data.name', required: true }, children: [] }],
            },
          ],
        },
        {
          id: nanoid(),
          name: ElCol,
          attr: { span: 12 },
          children: [
            {
              id: nanoid(),
              name: ElFormItem,
              attr: { label: '性别', prop: 'sex' },
              children: [{ id: nanoid(), name: ElInput, attr: { size: 'small', valueField: 'data.sex' }, children: [] }],
            },
          ],
        },
      ],
    },
    {
      id: nanoid(),
      name: ElButton,
      attr: {
        type: 'primary',
        label: '提交',
        size: 'small',
        onClick: () => {
          getData();
        },
      },
    },
  ],
};
const getData = () => {
  const formInstance = customRef.value.getInstance('formRef') as FormInstance;
  formInstance.validate((valid) => {
    if (valid) {
      alert(JSON.stringify(data.value));
    } else {
      ElMessage.error('表单校验失败');
    }
  });
};
</script>
